package com.qf.controller.filter;

import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author YDW
 * projectName:shopping
 * time:2022/4/19 11:10
 * description:自动登录过滤器
 */
@WebFilter( filterName = "AutoLoginFilter",value = "/*")
public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        /*
        * 0.验证是否登录了，如果没有，则自动登录；如果登录成功，则放行
        * 1.从cookie获取用户信息，解密
        * 2.验证用户名密码是否正确
        * 3.如果正确，登录成功
        */
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        //从session获取用户信息
        Object user=request.getSession().getAttribute("user");
        if(user!=null){
            filterChain.doFilter(request,response);
            return;
        }
        //执行过滤功能
        String username="";
        String password="";
        Cookie[] cookies=request.getCookies();
        if(cookies==null||cookies.length==0){
            response.sendRedirect("/index.jsp");
            filterChain.doFilter(request, response);
            return;
        }
        for(int i=0;i<cookies.length;i++){
            if("userinfo".equals(cookies[i].getName())){
                String value = Base64Utils.decode(cookies[i].getValue());
                String[] values = value.split("&");
                if(values!=null&&values.length==2){
                    username=values[0];
                    password=values[1];
                    UserService userService=new UserServiceImpl();
                    User login=userService.login(username,password);
                    if(login!=null){
                        request.getSession().setAttribute("user",login);
                    }
                    break;
                }
            }
        }



        //放行
        filterChain.doFilter(request,response);

    }

    @Override
    public void destroy() {

    }
}
